package top.frsf.pattern.c_behavioral.b_chainrespon.tomcat;

import lombok.Data;

import javax.servlet.*;
import java.io.IOException;
import java.util.Arrays;

/**
 * FilterChain
 *
 * @author FRSF
 * @since 2024/8/31 18:25
 */
@Data
public class ApplicationFilterChain implements FilterChain {

    /**
     * 位置指针
     */
    private int pos = 0;

    /**
     * 过滤器数量
     */
    private int n = 0;

    /**
     * 过滤器列表
     */
    private Filter[] filters = new Filter[0];

    /**
     * Servlet
     */
    private Servlet servlet;


    @Override
    public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
        if (this.pos < this.n) {
            this.filters[this.pos++].doFilter(request, response, this);
        }else {
            servlet.service(request, response);
        }
    }

    void addFilter(Filter filter) {
        Filter[] filtersCopy = Arrays.copyOf(this.filters, this.n + 1);
        filtersCopy[this.n++] = filter;
        this.filters = filtersCopy;
    }

}
